
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../vue.global.js"></script>
  <style>
    input {
      margin-bottom: 15px;
    }
  </style>
</head>

<body>
  <div id="app">
    商品：<input type="text" v-model="product.name" /><br />
    数量：<input type="text" v-model="product.num" /><br />
    价格：<input type="text" v-model="product.price" /><br />

    <button @click="addCar">添加到购物车</button>

    <ul>
      <li v-for="item in productList">
        <strong>{{item.name}}</strong>
        的数量是<strong>{{item.num}}</strong>,
        单价是<strong>{{item.price}}</strong>,
        小计：<u>{{item.num*item.price}}</u>
      </li>
      {{totalProduct}}
      <li>总计：总数----<u>{{totalNum}}</u>----总价----<u>{{totalPrice}}</u></li>
    </ul>


  </div>

  <script>
    new Vue({
      el: "#app",
      data: {
        product: {
          name: "",
          num: "",
          price: ""
        },
        productList: [
          {
            name: "牙刷",
            num: 100,
            price: 5
          },
          {
            name: "牙膏",
            num: 60,
            price: 10
          },
          {
            name: "镜子",
            num: 20,
            price: 50
          }
        ],
        totalNum: 0,
        totalPrice: 0
      },

      methods: {
        addCar () {
          if (JSON.stringify(this.product) != '{}') {
            this.productList.push(this.product)
            this.product = {};
          }
        }


      },
      computed: {

        totalProduct () {
          const length = this.productList.length
          if (length != 0) {
            for (i = 0; i < length; i++) {
              this.totalNum += parseInt(this.productList[i].num)
              this.totalPrice += parseInt(this.productList[i].num) * parseInt(this.productList[i].price)
            }
          }
        }

      }
    })
  </script>

</body>

</html>